<template>
	<view>
		<view class="comment-content" v-for="item in commentsList" :key="item.comment_id">
			<comments-box :comments="item" @reply="reply"></comments-box>
		</view>
		<release ref="popup" @submit="submit"></release>
		<uni-load-more :status="loading" iconType="snow" v-if="commentsList.length ===0 ||commentsList.length>10">
		</uni-load-more>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				commentsList: [],
				article_id: '',
				page: 1,
				pageSize: 10,
				loading: 'loading'
			}
		},
		onLoad(query) {
			this.article_id = query.id
			console.log(query.id)
			this.getComments()
		},
		methods: {
			getComments() {
				this.$api.get_comments({
					article_id: this.article_id,
					page: this.page,
					pageSize: this.pageSize
				}).then((res) => {
					let result = res.data
					if (result.length === 0) {
						this.loading = 'noMore'
						return
					}
					// 对象复制
					let oldFormData = JSON.parse(JSON.stringify(this.commentsList))
					oldFormData.push(...result)
					console.log(res);
					this.commentsList = oldFormData
				})
			},
			/**
			 * 更新评论
			 * @param {Object} content
			 */
			setUpdateComment(content) {
				uni.showLoading()
				// 数据重置，避免key重复，添加重复数据
				this.commentsList = []
				this.page = 1
				this.loading = 'loading'
				this.$api.update_comment({
					article_id: this.article_id,
					...content
				}).then((res) => {
					console.log(res)
					uni.hideLoading()
					uni.showToast({
						title: '评论成功',
						icon: 'none'
					})
					this.closeComment()
					this.getComments()
					this.replyFormData = {}

				})
			},
			openComment() {
				this.$refs.popup.openComment()
			},
			submit(content) {
				this.setUpdateComment({
					content,
					...this.replyFormData
				})
			},
			closeComment() {
				this.$refs.popup.closeComment()
			},
			//comment-box组件回传参数
			reply(e) {
				this.replyFormData = {
					"comment_id": e.comments.comment_id,
					"is_reply": e.is_reply
				}
				if (e.comments.reply_id) {
					this.replyFormData.reply_id = e.comments.reply_id
				}
				console.log(this.replyFormData);
				this.openComment()
			},
		}
	}
</script>

<style lang="scss">
	.comment-content {
		padding: 0 15px;
	}
</style>
